package com.xqboss.web.controller.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.xqboss.apps.domain.punch.PunchRule;
import com.xqboss.apps.domain.punch.PunchUserConfig;
import com.xqboss.apps.domain.user.UserIdentityRank;
import com.xqboss.apps.service.punch.PunchRuleService;
import com.xqboss.apps.service.punch.PunchUserConfigService;
import com.xqboss.apps.service.user.UserIdentityPermBasicService;
import com.xqboss.apps.service.user.UserIdentityRankService;
import com.xqboss.apps.vo.user.UserIdentityPermVo;
import com.xqboss.apps.vo.user.UserIdentityRankVo;
import com.xqboss.common.annotation.Log;
import com.xqboss.common.annotation.RepeatSubmit;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.domain.entity.SysUser;
import com.xqboss.common.enums.BusinessType;
import com.xqboss.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 用户身份-权限
 * </p>
 *
 * @author lujihaong
 * @since 2023-12-07
 */
@Slf4j
@Api(tags = "用户-身份权限管理")
@RestController("WebUserIdentityPermController")
@RequestMapping("/web/user/identity/perm")
public class UserIdentityPermController extends BaseController {

    @Autowired
    private UserIdentityPermBasicService userIdentityPermBasicService;

    @Autowired
    private UserIdentityRankService userIdentityRankService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private PunchUserConfigService punchUserConfigService;

    @Autowired
    private PunchRuleService punchRuleService;

    /**
     * 身份权限（装备升级上限、热豆转赠、邀返扳手）配置
     *
     * @return string
     */
    @PreAuthorize("@ss.hasPermi('web:user:identity:Perm:limit')")
    @Log(title = "身份权限（装备升级上限、热豆转赠、邀返扳手）配置", businessType = BusinessType.INSERT)
    @ApiOperation("身份权限（装备升级上限、热豆转赠、邀返扳手）配置")
    @PostMapping("/limit")
    public R<String> equipmentUpgradeLimit(@Validated @RequestBody UserIdentityPermVo vo) {
        try {
            this.userIdentityPermBasicService.equipmentUpgradeLimit(vo);
            return R.ok_msg("身份权限（装备升级上限、热豆转赠、邀返扳手）配置成功成功！");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }


    /**
     * 权限（装备升级上限、热豆转赠、邀返扳手）配置
     *
     * @return string
     */
    @PreAuthorize("@ss.hasPermi('web:user:identity:Perm:info')")
    @ApiOperation("权限（装备升级上限、热豆转赠、邀返扳手、身份等级列表）配置")
    @GetMapping("/info/{identityId}")
    public R<UserIdentityPermVo> equipmentUpgradeInfo(@PathVariable
                                                      @NotNull(message = "身份id不能为空")
                                                      @ApiParam(value = "身份id",required = true) Long identityId) {
        try {
            UserIdentityPermVo permVo = this.userIdentityPermBasicService.equipmentUpgradeInfo(identityId);
            return R.ok(permVo,"权限（装备升级上限、热豆转赠、邀返扳手）配置成功！");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 编辑用户身份等级
     */
    @RepeatSubmit(interval = 1000, justUrl = true)
    @PreAuthorize("@ss.hasPermi('web:user:identity:rank:edit')")
    @ApiOperation("用户身份等级-编辑")
    @PostMapping("/rank-edit")
    public R<Boolean> rankEdit(@Validated @RequestBody List<UserIdentityRankVo> params) {
        List<UserIdentityRank> ranks = BeanUtil.copyToList(params, UserIdentityRank.class);
        boolean b = userIdentityRankService.updateBatchById(ranks);
        if (b) {
            //编辑了等级对应打卡总次数（系数），重新设置该等级用户对应下次打卡时间及次数
            List<Long> rankIds = ranks.stream().map(UserIdentityRank::getId).collect(Collectors.toList());
            //查询所有对应等级的用户
            List<SysUser> userList = sysUserService.selectUserByRankId(rankIds);
            if (CollUtil.isNotEmpty(userList)) {
                List<Long> userIds = userList.stream().map(SysUser::getUserId).collect(Collectors.toList());
                //修改用户对应下次打卡时间及次数
                userIds.forEach(item -> {
                    PunchUserConfig config = punchUserConfigService.getConfig(item);
                    PunchRule rule = punchRuleService.getById(config.getPunchRuleId());
                    if (rule != null) {
                        //设置升级后用户可打卡总次数
                        rule.setPunchCount(userIdentityRankService.getUserRankIdentityPunchCount(item, rule.getPunchCount()));
                        punchUserConfigService.upgradeEditPunchCount(item, config, rule);
                    }
                });
            }
        }
        return R.ok(b);
    }
}
